<?php


namespace app\msgapi\service;

use app\msgapi\model\AuthRule;
use app\utils\Arr;

class HsmenuService extends BaseService
{
    public function __construct(AuthRule $authRule)
    {
        parent::__construct();
        $this->model = $authRule;
    }

    public function getLists()
    {
        $list = $this->model->order(['sort' => 'DESC', 'id' => 'ASC'])->select()->toArray();
        return success_json('成功',Arr::arrayToTree($list));
    }

    public function _save()
    {
        $data = input('post.');
        if($check = $this->model->validate($data)){
            return error_json($check);
        }
        $data['id'] = $data['id']?:($this->model::withTrashed()->max('id')+1);// 获取最大id值时包含软删除数据
        try{
            input('id/d')?$this->model::update($data):$this->model::create($data);
            return success_json('保存成功');
        } catch (\Exception $e){
            return error_json('保存失败，请重试');
        }
    }

    public function _delete($id, bool $force = false)
    {
        if($this->model->where(['pid'=>$id])->count() > 0) {
            return error_json('此菜单下存在子菜单，不可删除');
        }
        return parent::_delete($id, $force);
    }
}